package com.mxprojects.views
{
	import com.mxprojects.constructors.ButtonSmall;
	import com.mxprojects.constructors.DrawBorder;
	import com.mxprojects.constructors.PopupWindow;
	import com.mxprojects.constructors.PopupWindowNav;
	import com.mxprojects.constructors.SimpleTextField;
	import com.mxprojects.gui.DefaultDialog;
	import com.mxprojects.gui.PageNav;
	import com.mxprojects.gui.PrivateFooter;
	import com.mxprojects.gui.PrivateHeader;
	import com.mxprojects.gui.PrivateItem;
	import com.mxprojects.gui.PrivateSendMessage;
	import com.mxprojects.io.BoardCookie;
	import com.mxprojects.io.Config;
	import com.mxprojects.io.CustomEvent;
	import com.mxprojects.io.ServerHandler;
	import com.mxprojects.language.Language;
	import com.mxprojects.language.Word;
	
	import flash.display.Sprite;
	import flash.events.MouseEvent;
	import flash.events.TextEvent;
	
	public class PrivateMessages
	{		
		public static const NEW:int = 0;
		public static const READ:int = 1;
		public static const REPLIED:int = 2;
		public static const TRASH:int = 3;
		public static const DELETE:int = 4;
		
		private static const NAV_ELEMENTS:Array = new Array(Word.INBOX, Word.COMPOSE, Word.OUTBOX, Word.TRASH);
		
		protected static var popup:PopupWindow;
		protected static var popupNav:PopupWindowNav;
		protected static var dataToSend:Object;
		protected static var dataFromServer:Object;
		protected static var holder:Sprite = null;
		protected static var currentMessageID:int;
		protected static var currentLocation:String = Word.INBOX;
		
		private static var deleteButton:ButtonSmall;
				
		public static function load(recipient:String = ""):void {
			//build the UI
			if(popup == null){
				popup = new PopupWindow(Config.DEFAULT_POPUP_WIDTH, Config.DEFAULT_POPUP_HEIGHT, Language.main(Word.PRIVATE_MESSAGES), closePopup);

				//if the recipient is there then bypass the loading and go right to the sendMessage section
				if(recipient != ""){
					PrivateSendMessage.sendMessage(recipient);
				}else{
					//go to the inbox
					changeLocation(NAV_ELEMENTS[0]);
				}
				
				//start a timer to check your messages
			}			
		}
		
		private static function showMessages(location:String):void {
			//setup the content holder
			setupHolder();
			
			//show the nav
			buildTitleNav(location);
			
			//setup the nextY action
			var nextY:int = 0;
			
			//add the header that listens to locations
			var header:PrivateHeader = new PrivateHeader(location);
			holder.addChild(header);
			header.resize();
			nextY += header.height - DrawBorder.BOX_LINE_WIDTH;
			
			//put the private message there
			for(var i:int = 0; i < dataFromServer.messageCount; i++){
				var pm:PrivateItem = new PrivateItem(dataFromServer["pm"+i+"id"], 
													dataFromServer["pm"+i+"recipientID"],
													dataFromServer["pm"+i+"recipientStatus"],
													dataFromServer["pm"+i+"senderID"],
													dataFromServer["pm"+i+"senderStatus"],
													dataFromServer["pm"+i+"username"], 
													dataFromServer["pm"+i+"subject"], 
													dataFromServer["pm"+i+"message"], 
													dataFromServer["pm"+i+"sent"], 
													dataFromServer["pm"+i+"replied"],
													header);
				
				//resize and position
				holder.addChild(pm);
				pm.resize();
				pm.y = nextY;
				pm.name = PrivateItem.NAME + i;
				nextY += pm.height - Config.DEFAULT_LINE_HEIGHT;
			}
			
			//add the footer
			var footer:PrivateFooter = new PrivateFooter();
			holder.addChild(footer);
			footer.resize();
			footer.y = nextY;
			
			//add the delete button that will handle killing the messages
			deleteButton = new ButtonSmall(Language.main(Word.DELETE), deleteSelectedMessages);
			deleteButton.y = holder.height + Config.TEXT_PADDING/2;
			holder.addChild(deleteButton);
			
			//add a page nav
			if(int(dataFromServer.totalPages) > 1){
				var pageNav:SimpleTextField = new SimpleTextField(PageNav.createNav(dataFromServer.currentPage, dataFromServer.totalPages, -1, location, Word.PRIVATE_MESSAGES));
				pageNav.y = deleteButton.y;
				pageNav.x = holder.width - pageNav.width;
				holder.addChild(pageNav);
				
				//listen for the mouse clicks
				pageNav.addEventListener(TextEvent.LINK, navChangeLocation, false, 0, true);
			}
		}
		
		protected static function buildTitleNav(location:String = ""):void {
			popupNav = new PopupWindowNav(popup, location, NAV_ELEMENTS, navChangeLocation);
			
			//set the current location
			if(location != Word.COMPOSE){
				currentLocation = location;
			}
		}
		
		private static function navChangeLocation(event:TextEvent):void {
			//this will change the current location when clicked in the nav
			var chunks:Array = event.text.split(",");
			
			//let's get the page
			var pageNumber:int = chunks[2];
			if(pageNumber == 0){
				//if we don't have a page number, default to 1
				pageNumber = 1;
			}
			
			if(chunks[0] == Word.COMPOSE){
				PrivateSendMessage.sendMessage();
			}else{
				changeLocation(chunks[0], pageNumber);
			}
		}
		
		protected static function changeLocation(location:String, pageNumber:int = 1):void {			
			//set the username and password
			dataToSend = new Object();
			dataToSend.username = BoardCookie.getUser();
			dataToSend.password = BoardCookie.getPassword();
			dataToSend.privateMessagesPerPage = Config.PRIVATE_MESSAGES_PER_PAGE;
			
			//set the location
			dataToSend.location = location;
			dataToSend.page = pageNumber;
				
			//load the stuff
			var serverHandler:ServerHandler = new ServerHandler();
			serverHandler.transmitData("privatemessages.php", dataToSend);
			serverHandler.listenForData(processData);
		}
		
		protected static function processData(event:CustomEvent):void {
			//clear the old stuff
			dataFromServer = null;
			
			//set the var that's gonna hold all this stuff
			dataFromServer = event.getServerData();

			//let's see what kind of output we've got
			switch(dataFromServer.output){
				case "mySqlError":
					//throw up an error dialog
					DefaultDialog.show(dataFromServer.error, false);
				break;
				
				case Word.INBOX:
				case Word.OUTBOX:
				case Word.TRASH:
					//show the messages and junk
					showMessages(dataFromServer.output);
				break;
				
				case String(DELETE):
				case String(TRASH):
					changeLocation(currentLocation);
				break;
			}
		}
		
		private static function deleteSelectedMessages(event:MouseEvent):void {
			//this will move the messages to the deleted folder, if in the deleted folder it will remove them perminatly
			var messages:Array = new Array();
			var messageCount:int = dataFromServer.messageCount;
			
			for(var i:int = 0; i < messageCount; i++){
				var pm:PrivateItem = holder.getChildByName(PrivateItem.NAME + i) as PrivateItem;
				
				//let's figure out which messages we are deleting
				var messageValue:String = pm.checkBox.getValueIfChecked();
				
				//if we have something then let's make sure it ends up in the array
				if(messageValue != ""){
					messages.push(messageValue);
				}
			}
			
			//make sure we have IDs to delete
			if(messages.length > 0){
				if(currentLocation == Word.TRASH){
					//delete the message forever
					dataToSend.location = DELETE;
				}else{
					//just throw it in the trash
					dataToSend.location = TRASH;
				}
				
				//disable the delete button
				deleteButton.enabled = false;
				
				//send the messages and then giv'r
				dataToSend.messageID = messages.toString();
				dataToSend.senderID = "";
				dataToSend.recipientID = "";
				
				var serverHandler:ServerHandler = new ServerHandler();
				serverHandler.transmitData("privatemessages.php", dataToSend);
				serverHandler.listenForData(processData);
			}
		}
		
		protected static function setupHolder():void {
			//kill the holder if it's there
			removeHolder();
			
			//reset and add
			holder = new Sprite();
			holder.name = "holder";
			holder.x = Config.TEXT_PADDING*2;
			holder.y = popup.titleText.y + popup.titleText.height + Config.TEXT_PADDING;
			
			//draw an area to put stuff in
			holder.graphics.beginFill(0xffcc00, 0);
			holder.graphics.drawRect(0,0, popup.width - Config.TEXT_PADDING*4, 1);
			holder.graphics.endFill();
			
			//add it to the popup
			popup.addContent(holder);
		}
		
		protected static function removeHolder():void {
			//smoke it
			var pmHolder:Sprite = popup.getContent("holder") as Sprite;
			if(pmHolder != null){
				popup.removeContent(pmHolder);
			}
		}
		
		protected static function closePopup(event:MouseEvent = null):void {
			//remove it
			if(popup != null){
				//dump the data stuff
				dataToSend = null;
				
				popup.removeFromStage();
				popup = null;
				
				//refresh the header data so that it's not dated
				MXP3.header.refreshHeader();
			}
		}
		
		
	}
}